//导入时自定义名称为request
import request from '@/utils/request'


//如果 API 函数内部需要 ​处理异步逻辑​（如多个串联请求），才需要 async/await：
// export async function getGoodDetail(id) {
//   // 先获取基础信息
//   const goodInfo = await request({ url: `/good/${id}` });
//   // 再获取库存信息
//   const stockInfo = await request({ url: `/stock/${goodInfo.data.stockId}` });
//   return { ...goodInfo.data, stock: stockInfo.data };
// }


const list = (query)=>{
  return request.get('/warehouse/good/list', { params: query })
}

const getInfo = (id)=>{
  return request.get('/warehouse/good/' + id)
}


const addAndUpload = (data, files)=>{
  const formData = new FormData()
  formData.append('json', JSON.stringify(data))
  files.forEach((file) => {
    formData.append('files', file.raw) 
  })
  return request.post('/warehouse/good/addandupload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

const editAndUpload = (data,deleteIds, files)=>{
  const formData = new FormData()
  formData.append('json', JSON.stringify(data))


  // 方式 1：直接传逗号分隔的字符串（推荐）
  if (deleteIds && deleteIds.length > 0) {
    formData.append('deleteIds', deleteIds.join(','));
  }

  //多次 append（适用于 Spring MVC 自动收集）
  // deleteIds.forEach((id) => {
  //   formData.append('deleteIds', id)
  // })
  
  files.forEach((file) => {
    formData.append('files', file.raw) 
  })
    //   for (const [key, value] of formData.entries()) {
    //   console.log(key, value)
    // }
  return request.post('/warehouse/good/editandupload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}




// 删除【请填写功能名称】
const remove = (selectedIds)=> {
  return request.delete('/warehouse/good',{data:toRaw(selectedIds)})
  
  return request({
    //后端如果是@DeleteMapping("/{ids}") 参数@PathVariable Long[] ids，这里就写url: '/warehouse/good/' + selectedIds,
    url: '/warehouse/good',
    method: 'delete',
    data:toRaw(selectedIds) //传参直接传数组值即可
    //data: { ids: selectedIds }  //后端用一个DTO对象来接收
  })
}


const downloadByUrl = (fileInfo) => {
  return request.post('/warehouse/good/downloadbyurl', fileInfo)
}



export const API_GOOD = {
  list,
  getInfo,
  addAndUpload,
  editAndUpload,
  remove,
  downloadByUrl
}